// manager/pages/gridvisit/index.js
import config from '../../../utils/config';
import { request, uploadFile } from '../../../utils/request';
import util from '../../../common/util';
import WxValidate from '../../../common/WxValidate';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        baseUrl: config.baseUrl,
        // 日期限制
        startDate: "",
        endDate: "",
        startDate1: "",
        dict: {},
        // 业务字典
        busiList: [],
        keynoteList: [],
        reservationBusiList: [],
        form: {
            merchantId: "",
            // 1-个人，2-商户，3-企业，4-新型农业主体
            merchantType: "",
            coordinate: "",
            mapAddress: "",
            visitPic: "",
            ecardSemResult: "",
            newBusiness: "",
            failReason: "",
            reminderDate: "",
            hasReservationBusi: "",
            reservationBusiType: "",
            appointmentDate: "",

            remark: "",
        },
        // 个人信息
        personDetail: {},
        // 商户信息
        merchantDetail: {},
        // 企业信息
        enterpriseDetail: {},
        // 新型农业主体信息
        agricultureDetail: {},
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            ['form.merchantId']: options.merchantId,
            ['form.merchantType']: options.merchantType,
            startDate1: util.getDateByNumber(0),
        })
        this.initValidate();
        this.getLatLng();
        this.getSysConfigInfo();
        if(this.data.form.merchantType == 1){
            this.getPersonInfo();
        }
        if(this.data.form.merchantType == 2){
            this.getMerchantInfo();
        }
        if(this.data.form.merchantType == 3){
            this.getEnterpriseInfo();
        }
        if(this.data.form.merchantType == 4){
            this.getAgricultureInfo();
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['form.'+key]: e.detail.value
        })
    },

    /**
     * 选择框变化时
     */
    pickerChagne(e){
        let { key, value } = e.detail;
        let { form } = this.data;
        form[key] = value;
        if(key == "ecardSemResult"){
            form.newBusiness = "";
            form.failReason = "";
        }
        if(key == "hasReservationBusi"){
            form.reservationBusiType = "";
            form.appointmentDate = "";
        }
        this.setData({
            form
        })
    },

    /**
     * 已开通业务、营销重点选择
     */
    onCheckboxChange(e) {
        console.log(e)
        let { key, item } = e.currentTarget.dataset;
        let arr = this.data.form[key]?this.data.form[key].split(","):[];
        let index = arr.indexOf(item.dictValue);
        if(index != -1){
            arr.splice(index,1);
        }else{
            arr.push(item.dictValue);
        }
        this.setData({
            ['form.'+key]: arr.join(",")
        });
        if(key == "newBusiness"){
            this.getReservationBusiList(this.data.keynoteList);
        }
    },

    // 查看图片
    previewImage(e) {
        let { url } = e.currentTarget.dataset;
        let arr = this.data.form.visitPic?this.data.form.visitPic.split(","):[];
        let images = [];
        arr.forEach(item => {
            images.push(this.data.baseUrl+item)
        })
        wx.previewImage({
            current: url, // 当前显示图片的http链接
            urls: images // 需要预览的图片http链接列表
        })
    },

    /**
     * 日期选择
     */
    bindDateChange: function(e) {
        let { key } = e.currentTarget.dataset;
        this.setData({
            ['form.'+key]: e.detail.value
        })
    },
    // 个人信息
    getPersonInfo(){
        request({
            url: "/personMarketing/getPersonInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                id: this.data.form.merchantId
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    personDetail: res.data
                })
                this.getDictionaryInfo('ecard_person_business_tag');
                this.getDictionaryInfo('ecard_sem_result');
                this.getDictionaryInfo('ecard_has_reservation_busi');
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 商户信息
    getMerchantInfo(){
        request({
            url: "/merchantMarketing/getMerchantInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                id: this.data.form.merchantId
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    merchantDetail: res.data
                })
                // 获取字典
                this.getDictionaryInfo('ecard_merchant_business_tag');
                this.getDictionaryInfo('ecard_sem_result');
                this.getDictionaryInfo('ecard_has_reservation_busi');
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 企业信息
    getEnterpriseInfo(){
        request({
            url: "/enterpriseMarketing/getEnterpriseInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                id: this.data.form.merchantId
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    enterpriseDetail: res.data
                })
                // 获取字典
                this.getDictionaryInfo('ecard_enterprise_business_tag');
                this.getDictionaryInfo('ecard_sem_result');
                this.getDictionaryInfo('ecard_has_reservation_busi');
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    // 新型农业主体信息
    getAgricultureInfo(){
        request({
            url: "/agricultureMarketing/getAgricultureInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                id: this.data.form.merchantId
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    agricultureDetail: res.data
                })
                // 获取字典
                this.getDictionaryInfo('ecard_agriculture_business_tag');
                this.getDictionaryInfo('ecard_sem_result');
                this.getDictionaryInfo('ecard_has_reservation_busi');
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    
    /**
     * 获取时间限制
     */
    getSysConfigInfo() {
        request({
            url: "/commonApi/getConfigByMerchantType",
            data: {
                merchantType: this.data.form.merchantType
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    startDate: util.getDateByNumber(1),
                    endDate: util.getDateByNumber(Number(res.data.configValue)),
                    ['form.reminderDate']: util.getDateByNumber(Number(res.data.configValue)),
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 获取营销重点字典
     */
    /**
     * 获取字典
     */
    getDictionaryInfo(dictType) {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
                dictType
            }
        }).then(res => {
            if(res.code == 0){
                if([
                    'ecard_person_business_tag',
                    'ecard_merchant_business_tag',
                    'ecard_enterprise_business_tag',
                    'ecard_agriculture_business_tag'
                ].indexOf(dictType) != -1){
                    this.setData({
                        busiList: res.data
                    })
                    this.getKeynoteList(res.data);
                }else{
                    this.setData({
                        ['dict.'+dictType]: res.data
                    })
                }
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    // getDictionaryInfo() {
    //     request({
    //         url: "/commonApi/getDictionaryInfo",
    //         method: "GET",
    //         data: {
    //             dictType: "ecard_merchant_business_tag"
    //         }
    //     }).then(res => {
    //         if(res.code == 0){
    //             this.setData({
    //                 busiList: res.data
    //             })
    //             this.getKeynoteList(res.data);
    //         }
    //         return request({
    //             url: "/commonApi/getDictionaryInfo",
    //             method: "GET",
    //             data: {
    //                 dictType: "ecard_sem_result"
    //             }
    //         })
    //     }).then(res => {
    //         if(res.code == 0){
    //             this.setData({
    //                 semResultList: res.data
    //             })
    //         }
    //         return request({
    //             url: "/commonApi/getDictionaryInfo",
    //             method: "GET",
    //             data: {
    //                 dictType: "ecard_has_reservation_busi"
    //             }
    //         })
    //     }).then(res => {
    //         if(res.code == 0){
    //             this.setData({
    //                 hasnoList: res.data
    //             })
    //         }
    //     }).catch(error => {
    //         // console.log(error)
    //     })
    // },

    // 获取营销重点
    getKeynoteList(list){
        if(this.data.form.merchantType == 1){
            let keynoteList = [];
            let arr = this.data.personDetail.perBusinessLabel?this.data.personDetail.perBusinessLabel.split(","):[];
            list.forEach(item => {
                if(arr.indexOf(item.dictValue)==-1){
                    keynoteList.push(item)
                }
            })
            this.setData({
                keynoteList
            })
            this.getReservationBusiList(keynoteList);
        }
        if(this.data.form.merchantType == 2){
            let keynoteList = [];
            let arr = this.data.merchantDetail.businessLabel?this.data.merchantDetail.businessLabel.split(","):[];
            list.forEach(item => {
                if(arr.indexOf(item.dictValue)==-1){
                    keynoteList.push(item)
                }
            })
            this.setData({
                keynoteList
            })
            this.getReservationBusiList(keynoteList);
        }
        if(this.data.form.merchantType == 3){
            let keynoteList = [];
            let arr = this.data.enterpriseDetail.entBusinessLabel?this.data.enterpriseDetail.entBusinessLabel.split(","):[];
            list.forEach(item => {
                if(arr.indexOf(item.dictValue)==-1){
                    keynoteList.push(item)
                }
            })
            this.setData({
                keynoteList
            })
            this.getReservationBusiList(keynoteList);
        }
        if(this.data.form.merchantType == 4){
            let keynoteList = [];
            let arr = this.data.agricultureDetail.agrBusinessLabel?this.data.agricultureDetail.agrBusinessLabel.split(","):[];
            list.forEach(item => {
                if(arr.indexOf(item.dictValue)==-1){
                    keynoteList.push(item)
                }
            })
            this.setData({
                keynoteList
            })
            this.getReservationBusiList(keynoteList);
        }
    },
    getReservationBusiList(list){
        let reservationBusiList = [];
        let arr = this.data.form.newBusiness?this.data.form.newBusiness.split(","):[];
        let farr = this.data.form.reservationBusiType?this.data.form.reservationBusiType.split(","):[];
        list.forEach(item => {
            if(arr.indexOf(item.dictValue)==-1){
                reservationBusiList.push(item)
            }
        })
        arr.forEach(item => {
            let index = farr.indexOf(item);
            if(index != -1){
                farr.splice(index,1);
            }
        })
        this.setData({
            reservationBusiList,
            ['form.reservationBusiType']: farr.join(",")
        })
    },

    // 获取经纬度
    getLatLng(){
        let that = this;
        wx.getSetting({
            success: (res) => {
                console.log(res)
                if (res.authSetting['scope.userLocation'] == false) {//非初始化进入该页面,且未授权
                    wx.showModal({
                        title: '是否授权当前位置',
                        content: '需要获取您的地理位置，请确认授权',
                        success: function (res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success: function (data) {
                                        // console.log(data);
                                        if (data.authSetting["scope.userLocation"] == true) {
                                            that.getLocation();
                                        }
                                    }
                                })
                            }
                        }
                    })
                } else {//初始化进入
                    // console.log("KKKKK") 
                    that.getLocation();
                }
            }
        })
    },
    getLocation(){
        const that = this;
        wx.getLocation({
            type: 'gcj02',
            altitude: true,
            isHighAccuracy: true,
            success (res) {
                that.getCoordinatePositionInfo(res.latitude,res.longitude)
            },
            complete: function(res) {
                if(res.errMsg == "getLocation:fail auth deny"){
                    // wx.showToast({
                    //     title: '获取定位失败',
                    //     icon: 'none',
                    //     duration: 2000
                    // });
                }
            }
        })
    },
    getCoordinatePositionInfo(latitude,longitude){
        // const that = this;
        let { form } = this.data;
        request({
            url: "/commonApi/getCoordinatePositionInfo",
            method: "GET",
            data: {
                coordinate: `${latitude},${longitude}`
            }
        }).then(res => {
            if(res.code == 0){
                form.coordinate = `${latitude},${longitude}`;
                form.mapAddress = res.data.address;
                this.setData({
                    form
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 商户图片或营业执照图片上传
    uploadImage(e) { // 拍摄或从相册选取上传
        let { key } = e.currentTarget.dataset;
        let that = this;
        let arr = this.data.form.visitPic?this.data.form.visitPic.split(","):[];
        if(arr.length>=5){
            this.showModal({
                msg: "拜访照片最多上传5张"
            })
            return
        }
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['compressed'],
            sourceType: ['camera'],
            success(res) {
                wx.compressImage({
                    src: res.tempFilePaths[0], // 图片路径
                    quality: 40, // 压缩质量
                    success(res1) {
                        uploadFile({
                            url: "/commonApi/imageUploadAddWatermark",
                            filePath: res1.tempFilePath,
                            name: "imgfile",
                            formData: {
                                coordinate: that.data.form.coordinate,
                                watermark: that.data.form.mapAddress,
                                fileName: key
                            }
                        }).then(res => {
                            if(res.code == 0){
                                let arr = that.data.form[key]?that.data.form[key].split(","):[];
                                arr.push(res.data)
                                that.setData({
                                    ['form.'+key]: arr.join(",")
                                })
                            }
                        }).catch(error => {
                            // console.log(error)
                        })
                    }
                })
            }
        })
    },
    // 保存
    save(e) {
        // 传入表单数据，调用验证方法
        if (!this.WxValidate.checkForm(this.data.form)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }
        if(this.data.form.ecardSemResult == 1){
            if(!this.data.form.newBusiness){
                this.showModal({
                    msg: "请选择本次营销成功"
                })
                return
            }
        }else{
            if(!this.data.form.failReason){
                this.showModal({
                    msg: "请输入失败原因"
                })
                return
            }
        }
        if(!this.data.form.reminderDate){
            this.showModal({
                msg: "请选择下次回访日期"
            })
            return
        }
        if(!this.data.form.hasReservationBusi){
            this.showModal({
                msg: "请选择有无预约业务"
            })
            return
        }
        if(this.data.form.hasReservationBusi == 1){
            if(!this.data.form.reservationBusiType){
                this.showModal({
                    msg: "请选择预约业务"
                })
                return
            }
            if(!this.data.form.appointmentDate){
                this.showModal({
                    msg: "请选择业务预约日期"
                })
                return
            }
        }
        request({
            url: `/merchantMarketing/addMerchantVisitInfo`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: this.data.form
        }).then(res => {
            if(res.code == 0){
                wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    mask: true,
                    duration: 2000
                });
                setTimeout(()=>{
                    wx.navigateBack()
                },2000)
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 表单验证
    initValidate() {
        // 验证字段的规则
        const rules = {
            coordinate: {
                required: true
            },
            visitPic: {
                required: true
            },
            ecardSemResult: {
                required: true
            },
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = {
            coordinate: {
                required: '打卡定位'
            },
            visitPic: {
                required: '请上传图片'
            },
            ecardSemResult: {
                required: '请选择营销成果'
            },
        }
        // 创建实例对象
        this.WxValidate = new WxValidate(rules, messages)
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },
})